#include <vector>
#include <iostream>
#include "snake.h"
#include "map.h"
#include <random>
#include <chrono>
using namespace std;
int MAP_HEIGHT = 40;
int MAP_WIDTH = 80;
std::vector<std::vector<char>> gameMap(MAP_HEIGHT+1, std::vector<char>(MAP_WIDTH+1));

void createMap() {
    for(int i = 0; i <= MAP_HEIGHT; i++) {
        for(int j = 0; j <= MAP_WIDTH; j++) {
            if(i == 0 || i == MAP_HEIGHT || j == 0 || j == MAP_WIDTH) {
                gameMap[i][j] = '#'; // 边界线
            } 
            else {
                gameMap[i][j] = ' '; 
            }
        }
    }
}

Food food;
void createFood() {
    const char FOOD_CHAR = 'F';
    const int MAP_WIDTH = 80;  
    const int MAP_HEIGHT = 40; 

    // 混合种子增强随机性
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::mt19937 gen(seed);
    
    // 生成奇数坐标避免字符截断[1](@ref)
    std::uniform_int_distribution<> disX(1, (MAP_WIDTH-2)/2); 
    std::uniform_int_distribution<> disY(1, MAP_HEIGHT-2);

    int foodX, foodY;
    bool isValid;
    int maxAttempts = 100; // 防止无限循环
    
    do {
        foodX = disX(gen) * 2; // 生成偶数坐标
        foodY = disY(gen);
        isValid = true;

        // 校验坐标有效性
        if (foodX <= 0 || foodX >= MAP_WIDTH || 
            foodY <= 0 || foodY >= MAP_HEIGHT) {
            isValid = false;
            continue;
        }

        // 检查蛇身和障碍物
        for (const auto& segment : snake) {
            if (segment.x == foodX && segment.y == foodY) {
                isValid = false;
                break;
            }
        }
        if (gameMap[foodY][foodX] != ' ') isValid = false;

    } while (!isValid && --maxAttempts > 0);

    if (isValid) {
        gameMap[foodY][foodX] = FOOD_CHAR;
        food.x = foodX;
        food.y = foodY;
    } else {
        // 处理生成失败（如扩大地图范围）
    }
}
